import {
  GetCommentParamsType,
  getCommentByIdAPI,
  sendCommentAPI,
  likeCommentAPI,
  dislikeCommentAPI,
} from '@/api/comment';
import { AppDispatch } from '..';
import { ActionType, CommentType } from '../reducer/comment';

export const getCommentByIdAction = (params: GetCommentParamsType) => {
  return async (dispatch: AppDispatch) => {
    const res = await getCommentByIdAPI(params);
    dispatch({ type: 'comment/saveList', payload: res.data.results });
  };
};

export const clearCommenAction = (): ActionType => ({ type: 'comment/clearList' });

export const saveOriginCommentAction = (comment: CommentType): ActionType => {
  return {
    type: 'comment/saveOriginComment',
    payload: comment,
  };
};

export const clearOriginCommentAction = (): ActionType => {
  return {
    type: 'comment/saveOriginComment',
    payload: {} as CommentType,
  };
};

export const sendCommentAction = (target: string, content: string, art_id?: string) => {
  return async () => {
    await sendCommentAPI({ target, content, art_id });
  };
};

export const getReplyCommentByIdAction = (com_id: string) => {
  return async (dispatch: AppDispatch) => {
    const res = await getCommentByIdAPI({ type: 'c', source: com_id });
    dispatch({ type: 'comment/saveReplyList', payload: res.data });
  };
};

export const clearReplyCommentAction = (): ActionType => ({
  type: 'comment/clearReplyList',
});

export const likeCommentAction = (target: string, isLiking: boolean) => {
  return async () => {
    if (!isLiking) {
      await likeCommentAPI(target);
      return;
    }
    await dislikeCommentAPI(target);
  };
};
